package petertel.pbx.conf.logger;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

import petertel.pbx.conf.ConfigItem;
import petertel.pbx.conf.logger.Loglevel.Type;
import petertel.pbx.utils.ParserUtils;

public class Logfile extends ConfigItem implements Serializable {

	private static final long serialVersionUID = -9216470565851292765L;

	private String filename;
	private List<Loglevel> loglevels = new ArrayList<Loglevel>();

	private petertel.pbx.utils.ConfigItem config;
	{
		for (Loglevel.Type type : Loglevel.Type.values()) {
			Loglevel loglevel = new Loglevel();
			loglevel.setType(type);
			loglevels.add(loglevel);
		}
	}

	public Logfile() {

	}

	public Logfile(String filename, Flag flag, Loglevel... loglevels) {
		setFilename(filename);
		setFlag(flag);
		for (int i = 0; i < loglevels.length; i++) {
			this.loglevels.add(loglevels[i]);
		}
	}

	public Logfile(petertel.pbx.utils.ConfigItem config) {
		this.config = config;
	}

	public String getFilename() {
		return ParserUtils.getPairName(config.getLine());
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public List<Loglevel> getLoglevels() {
		List<Loglevel> loglevels = new ArrayList<Loglevel>();
		Set<Loglevel.Type> set = toSet(ParserUtils.getPairValue(config
				.getLine()));
		for (Loglevel.Type llt : Loglevel.Type.values()) {
			Loglevel ll = new Loglevel();
			ll.setType(llt);
			ll.setChecked(set.contains(llt));
			loglevels.add(ll);
		}
		return loglevels;
	}

	private Set<Type> toSet(String pairValue) {
		Set<Type> set = new HashSet<Type>();
		StringTokenizer tokenizer = new StringTokenizer(pairValue, ",");
		while (tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken().trim();
			if (token.equals("")) {
				continue;
			}
			set.add(Type.valueOf(token));
		}
		return set;
	}

	public void setLoglevels(List<Loglevel> loglevels) {
		this.loglevels = loglevels;
	}

	@Override
	public String write() {
		String ret = "";
		ret += filename + " => ";
		boolean isFirst = true;
		for (int i = 0; i < loglevels.size(); i++) {
			Loglevel loglevel = loglevels.get(i);
			if (!loglevel.isChecked()) {
				continue;
			}
			if (isFirst) {
				;
			} else {
				ret += ", ";
			}
			ret += loglevel.getType();
			isFirst = false;
		}
		return ret;
	}

	@Override
	public String toString() {
		String ret = "";
		ret += "[" + getLineno() + "][" + getFlag() + "]";
		ret += getFilename() + ":";
		for (int i = 0; i < loglevels.size(); i++) {
			ret += " " + loglevels.get(i);
		}
		ret += "\n";
		return ret;
	}

}
